package com.yxinsur.imc.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxinsur.imc.business.domain.ImcOrderPersonEndorse;
import com.yxinsur.imc.business.enums.*;
import com.yxinsur.imc.business.form.OrderEndorseForm;
import com.yxinsur.imc.business.form.OrderPersonEndorseForm;
import com.yxinsur.imc.business.mapper.ImcOrderMapper;
import com.yxinsur.imc.business.mapper.ImcOrderPersonEndorseMapper;
import com.yxinsur.imc.business.service.IImcOrderPersonEndorseService;
import com.yxinsur.imc.common.core.domain.AjaxResult;
import com.yxinsur.imc.common.utils.SecurityUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 保单人员批单Service业务层处理
 *
 * @author imc
 * @date 2021-10-09
 */
@Service
public class ImcOrderPersonEndorseServiceImpl extends ServiceImpl<ImcOrderPersonEndorseMapper, ImcOrderPersonEndorse> implements IImcOrderPersonEndorseService {
    @Autowired
    private ImcOrderPersonEndorseMapper imcOrderPersonEndorseMapper;
    @Autowired
    private ImcOrderMapper imcOrderMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 新增保单人员批单
     *
     * @param endorseForm 批单信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult addImcOrderPersonEndorse(OrderEndorseForm endorseForm) {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        ImcOrderPersonEndorseMapper pm = session.getMapper(ImcOrderPersonEndorseMapper.class);
        Long orderId = endorseForm.getOrderId();

        // 删除人员信息
        List<ImcOrderPersonEndorse> oldPersonEndorseList = imcOrderPersonEndorseMapper.listOrderPersonEndorseByOrderId(orderId);
        if (CollUtil.isNotEmpty(oldPersonEndorseList)) {
            for (ImcOrderPersonEndorse item : oldPersonEndorseList) {
                item.setUpdateTime(DateUtil.date());
                item.setUpdateId(SecurityUtils.getUsername());
                pm.deleteImcOrderPersonEndorseById(item);
            }
        }

        // 保存人员信息
        String serialId = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        List<ImcOrderPersonEndorse> personEndorseList = savePersonEndorse(endorseForm, orderId, serialId);
        for (ImcOrderPersonEndorse personEndorse : personEndorseList) {
            pm.insertImcOrderPersonEndorse(personEndorse);
        }
        session.commit();
        return AjaxResult.success();
    }

    /**
     * 保存保单人员批单
     *
     * @param endorseForm 批单信息
     * @param orderId     保单ID
     * @param serialId    批单流水号
     * @return List<ImcOrderPersonEndorse>
     */
    private List<ImcOrderPersonEndorse> savePersonEndorse(OrderEndorseForm endorseForm, Long orderId, String serialId) {
        List<ImcOrderPersonEndorse> personEndorseList = CollUtil.newArrayList();
        // 投保人
        List<OrderPersonEndorseForm> applicantFormList = endorseForm.getApplicantFormList();
        // 默认投保人
        OrderPersonEndorseForm defaultApplicant = new OrderPersonEndorseForm();
        if (CollUtil.isNotEmpty(applicantFormList)) {
            // 第一个投保人为默认投保人
            defaultApplicant = applicantFormList.get(0);
            defaultApplicant.setIsDefalut(IsDefaultEnum.Y.getCode());
            for (OrderPersonEndorseForm item : applicantFormList) {
                ImcOrderPersonEndorse applicantEndorse = new ImcOrderPersonEndorse();
                BeanUtil.copyProperties(item, applicantEndorse, CopyOptions.create().ignoreCase().setIgnoreNullValue(true));
                applicantEndorse.setSerialId(serialId);
                applicantEndorse.setOrderId(orderId);
                applicantEndorse.setIsDefalut(StrUtil.isNotBlank(applicantEndorse.getIsDefalut()) ? IsDefaultEnum.Y.getCode() : IsDefaultEnum.N.getCode());
                applicantEndorse.setOrderPersonType(OrderPersonTypeEnum.A.getCode());
                applicantEndorse.setIsDeleted(IsDeletedEnum.N.getCode());
                applicantEndorse.setCreateTime(DateUtil.date());
                applicantEndorse.setCreateId(SecurityUtils.getUsername());
                applicantEndorse.setUpdateTime(DateUtil.date());
                applicantEndorse.setUpdateId(SecurityUtils.getUsername());
                applicantEndorse.setTenantId(SecurityUtils.getTenantId());
                personEndorseList.add(applicantEndorse);
            }
        }
        // 被保人
        List<OrderPersonEndorseForm> insurantList = endorseForm.getInsurantFormList();
        if (CollUtil.isNotEmpty(insurantList)) {
            // 默认被保人（第一个投保人为默认被保人）
            OrderPersonEndorseForm defaultInsurant = insurantList.get(0);
            defaultInsurant.setIsDefalut(IsDefaultEnum.Y.getCode());
            for (OrderPersonEndorseForm item : insurantList) {
                ImcOrderPersonEndorse insurantEndorse = new ImcOrderPersonEndorse();
                // 判断被保人与投保人关系为否为本人，为本人则取默认投保人的值
                if (item.getRelationWithApplicant().equals(OrderPersonRelationEnum.本人.name())) {
                    BeanUtil.copyProperties(defaultApplicant, insurantEndorse, CopyOptions.create().ignoreCase().setIgnoreNullValue(true));
                    insurantEndorse.setIsSameApplicant(YesOrNoEnum.Y.name());
                    insurantEndorse.setRelationWithApplicant(OrderPersonRelationEnum.本人.name());
                } else {
                    BeanUtil.copyProperties(item, insurantEndorse, CopyOptions.create().ignoreCase().setIgnoreNullValue(true));
                    insurantEndorse.setIsSameApplicant(YesOrNoEnum.N.name());
                }
                insurantEndorse.setOrderId(orderId);
                insurantEndorse.setSerialId(serialId);
                insurantEndorse.setIsDefalut(StrUtil.isNotBlank(insurantEndorse.getIsDefalut()) ? IsDefaultEnum.Y.getCode() : IsDefaultEnum.N.getCode());
                insurantEndorse.setOrderPersonType(OrderPersonTypeEnum.B.getCode());
                insurantEndorse.setIsDeleted(IsDeletedEnum.N.getCode());
                insurantEndorse.setCreateTime(DateUtil.date());
                insurantEndorse.setCreateId(SecurityUtils.getUsername());
                insurantEndorse.setUpdateTime(DateUtil.date());
                insurantEndorse.setUpdateId(SecurityUtils.getUsername());
                insurantEndorse.setTenantId(SecurityUtils.getTenantId());
                personEndorseList.add(insurantEndorse);
            }
        }
        // 受益人
        List<OrderPersonEndorseForm> favourList = endorseForm.getFavourFormList();
        if (CollUtil.isNotEmpty(favourList)) {
            for (OrderPersonEndorseForm item : favourList) {
                ImcOrderPersonEndorse favourEndorse = new ImcOrderPersonEndorse();
                // 是否同投保人
                if (item.getIsSameApplicant().equals(YesOrNoEnum.Y.name())) {
                    BeanUtil.copyProperties(defaultApplicant, favourEndorse, CopyOptions.create().ignoreCase().setIgnoreNullValue(true));
                    favourEndorse.setBenefitOrder(item.getBenefitOrder());
                    favourEndorse.setBenefitRate(item.getBenefitRate());
                    favourEndorse.setIsSameApplicant(YesOrNoEnum.Y.name());
                    favourEndorse.setRelationWithApplicant(OrderPersonRelationEnum.本人.name());
                } else {
                    BeanUtil.copyProperties(item, favourEndorse, CopyOptions.create().ignoreCase().setIgnoreNullValue(true));
                }
                favourEndorse.setOrderId(orderId);
                favourEndorse.setSerialId(serialId);
                favourEndorse.setOrderPersonType(OrderPersonTypeEnum.C.getCode());
                favourEndorse.setIsLegalBeneficiary(YesOrNoEnum.N.getCode().toString());
                favourEndorse.setIsDefalut(IsDefaultEnum.N.getCode());
                favourEndorse.setIsDeleted(IsDeletedEnum.N.getCode());
                favourEndorse.setCreateTime(DateUtil.date());
                favourEndorse.setCreateId(SecurityUtils.getUsername());
                favourEndorse.setUpdateTime(DateUtil.date());
                favourEndorse.setUpdateId(SecurityUtils.getUsername());
                favourEndorse.setTenantId(SecurityUtils.getTenantId());
                personEndorseList.add(favourEndorse);
            }
        }
        return personEndorseList;
    }
}
